<?php
/***/
namespace app\admin\controller;

use app\admin\model\Auth;
use app\admin\model\BusPreOrder;
use app\admin\model\BusPreOrderPhone;
use app\admin\model\Channel;
use think\Db;

/**
 * 订单管理
 * @Author    lf
 */
class Orders extends Father {
	/**
	 * 首页
	 * @创建     lf
	 * @修改
	 * @修改时间   2025-08-20T17:05:49+0800
	 * @描述
	 * @return [type]                   [description]
	 */
	public function index() {
		//默认时间
		$st = date('Y-m-d 00:00:00', strtotime("-7 day"));
		if (request()->isPost()) {
			//允许接收的请求变量
			$request = request()->only([
				'page'        => 1,
				'limit'       => 20,
				'create_time' => $st,
				'et'          => date('Y-m-d H:i:s'),
				'channel_id'  => '',
				'country'     => '',
				'phone'       => '',
			]);

			//查询数据
			$orderm = new BusPreOrder;
			$list   = $orderm->getOrderAll($request);
			return json([
				"code"  => 0,
				"msg"   => "",
				"count" => $list['total'],
				"data"  => $list['data'],
			]);
		} else {
			$channelInfo = Channel::field('channel_id,company_name')->where('p_id', session('relate_id'))->whereOr('channel_id', session('relate_id'))->select();

			$this->assign('chas', $channelInfo);
			$this->assign('countryData', db('bus_country_code')->field('*')->select());
			$this->assign('configData', ['st' => $st, 'et' => date('Y-m-d 23:59:59')]);
			return $this->fetch();
		}
	}
	/**
	 * 导出订单
	 * @Author   lf
	 * @DateTime 2018-07-26T11:20:38+0800
	 * @return   [type]                   [description]
	 */
	public function putoutNum() {
		set_time_limit(0); //超时不限制
		ini_set("memory_limit", "300M");
		//文件名
		$fileName = "daw_order/" . date('YmdHis', time()) . rand(100, 999);
		// header('Content-Type: application/vnd.ms-execl');
		// header('Content-Disposition: attachment;filename="订单号码' . basename($fileName) . '.csv');

		try {
			//默认时间
			// $onlyrequest = [['st', $st], ['et', date('Y-m-d H:i:s')], ['sta', ''], ['cha', ''], ['hm', ''], ['pla', ''], ['field', ''], ['pcode', ''], ['isp_host', '']];
			$st = date('Y-m-d 00:00:00', strtotime("-7 day"));

			//允许接收的请求变量
			$request = request()->only([
				'page'        => 1,
				'limit'       => 20,
				'create_time' => $st,
				'et'          => date('Y-m-d H:i:s'),
				'pcode'       => '',
				'channel_id'  => '',
				'country'     => '',
				'phone'       => '',
				'field'       => '',
			]);
			trace('用户' . session('username') . '导出订单条件：' . json_encode($request, JSON_UNESCAPED_UNICODE), 'info');

			$request['field'] = base64_decode($request['field']);
			$request['field'] = explode(',', $request['field']);
			// halt($request['field']);
			//获取字段
			$orderInfo = [
				['field' => 'phone', 'title' => '手机号码', 'fieldname' => 'pho.phone'],
				['field' => 'content', 'title' => '发送内容', 'fieldname' => 'sms.bus_push_sms'],
				['field' => 'status', 'title' => '号码状态', 'fieldname' => 'pho.order_phone_code'],
				['field' => 'country', 'title' => '国家', 'fieldname' => 'pho.country'],
				['field' => 'msg', 'title' => '错误描述', 'fieldname' => 'pho.order_phone_msg'],
				['field' => 'create_time', 'title' => '下单时间', 'fieldname' => 'pho.create_time'],

			];
			//真正需要的字段
			$pullorderInfo = [];
			foreach ($orderInfo as $key => $value) {
				if (in_array($value['field'], $request['field'])) {
					$pullorderInfo[] = $value;
				}
			}

			$fieldData        = array_column($pullorderInfo, 'field'); //字段名
			$titleData        = array_column($pullorderInfo, 'title'); //表头
			$request['field'] = implode(',', array_column($pullorderInfo, 'fieldname')); //表字段

			//文件名组
			$fileNameArr = [];

			//生成csv
			$fp = fopen('php://output', 'a');
			fwrite($fp, chr(0xEF) . chr(0xBB) . chr(0xBF)); //转码
			fputcsv($fp, ['导出时间', "\t" . $request['create_time'] . '至' . $request['et']]);
			//输出头
			fputcsv($fp, $titleData);
			//实例化
			$orderm           = new BusPreOrder;
			$i                = 1;
			$request['limit'] = 5000; //每次
			$jiange           = 0; //间隔10保存一次
			$fileindex        = 1; //文件后缀
			//循环输出
			while ($i <= 200) {
				//分页取数据
				$request['page'] = $i;
				$list            = $orderm->getOrderPhoneAll($request);
				//查询为空，退出
				if (count($list) <= 0) {
					$i = 100000;
					break;
				}
				foreach ($list as $key => $value) {
					//全部单元格设置文本形式
					$arr = [];
					foreach ($fieldData as $k => $v) {
						if ($v) {
							$value[$v] = str_replace(",", "，", $value[$v]);
						}

						$arr[] = "\t" . $value[$v];
					}
					//输出
					fputcsv($fp, $arr);
				}

				//输出缓存
				ob_flush();
				flush();

				if (count($list) < $request['limit']) {
					$i = 100000;
					break;
				}

				unset($list);
				unset($value);
				$i++;
			}

			if (isset($fp)) {
				fclose($fp);
				unset($fp);
			}
			exit;

		} catch (Exception $e) {
			echo "导出文件出错了";
		}

		exit;

	}

	/**
	 * 导出订单 方案2 zip导出
	 * @Author   lf
	 * @DateTime 2018-07-26T11:20:38+0800
	 * @return   [type]                   [description]
	 */
	// public function putout222() {
	// 	set_time_limit(0); //超时不限制
	// 	ini_set("memory_limit", "520M");
	// 	//   ini_set("display_errors","On");
	// 	// error_reporting(E_ALL);
	// 	//文件名
	// 	$fileName = "daw_order/" . date('YmdHis', time()) . rand(100, 999);
	// 	header('Content-Type: application/vnd.ms-execl');
	// 	header('Content-Disposition: attachment;filename="' . basename($fileName) . '.csv');

	// 	try {
	// 		//默认时间
	// 		$st = date('Y-m-d H:i:s', strtotime("-30 minute"));
	// 		//允许接收的请求变量
	// 		$onlyrequest = [['st', $st], ['et', date('Y-m-d H:i:s')], ['sta', ''], ['cha', ''], ['hm', ''], ['pla', ''], ['field', '']];
	// 		$request     = $this->getRequests($onlyrequest, 'GET');
	// 		trace('用户' . session('username') . '导出订单条件：' . json_encode($request, JSON_UNESCAPED_UNICODE), 'info');

	// 		$request['field'] = base64_decode($request['field']);
	// 		$request['field'] = explode(',', $request['field']);

	// 		//获取字段
	// 		$orderInfo = $this->orderInfo(['phones', 'success_num']);
	// 		//真正需要的字段
	// 		$pullorderInfo = [];
	// 		foreach ($orderInfo as $key => $value) {
	// 			if (in_array($value['field'], $request['field'])) {
	// 				$pullorderInfo[] = $value;
	// 			}
	// 		}

	// 		$fieldData = array_column($pullorderInfo, 'field'); //字段名
	// 		$titleData = array_column($pullorderInfo, 'title'); //表头

	// 		//文件名组
	// 		$fileNameArr = [];

	// 		//生成csv
	// 		//       $fp = fopen('php://output', 'a');
	// 		// fwrite($fp, chr(0xEF).chr(0xBB).chr(0xBF));//转码
	// 		//输出头
	// 		// fputcsv($fp, $titleData);
	// 		//实例化
	// 		$orderm           = new OrdersM;
	// 		$i                = 1;
	// 		$request['limit'] = 10000; //每次
	// 		$jiange           = 0; //间隔10保存一次
	// 		$fileindex        = 1; //文件后缀
	// 		//循环输出
	// 		while ($i <= 200) {
	// 			//分页取数据
	// 			// $list   = $orderm->getOrderPutout($request,$i);
	// 			$request['page'] = $i;
	// 			$listData        = $orderm->getOrderAll($request);
	// 			$list            = $listData['data'];
	// 			//查询为空，退出
	// 			if (count($list) <= 0) {
	// 				$i = 100000;
	// 				break;
	// 			}

	// 			if ($jiange == 0) {
	// 				//生成临时文件
	// 				$fileNameArr[] = $fileName . '_' . $fileindex . '.csv';
	// 				$fp            = fopen($fileName . '_' . $fileindex . '.csv', 'w');
	// 				$fileindex++;

	// 				fwrite($fp, chr(0xEF) . chr(0xBB) . chr(0xBF)); //转码
	// 				//输出表头
	// 				fputcsv($fp, $titleData);
	// 			}

	// 			foreach ($list as $key => $value) {
	// 				//全部单元格设置文本形式
	// 				$arr = [];
	// 				foreach ($fieldData as $k => $v) {
	// 					// dump($v);
	// 					$value[$v] = str_replace(",", "，", $value[$v]);
	// 					$arr[]     = "\t" . $value[$v];
	// 				}
	// 				//输出
	// 				fputcsv($fp, $arr);
	// 			}

	// 			if ($jiange >= 9) {
	// 				//关闭文件
	// 				fclose($fp);
	// 				unset($fp);
	// 				//循环一个新的文件
	// 				$jiange = 0;
	// 			} else {
	// 				$jiange++;
	// 			}

	// 			//输出缓存
	// 			ob_flush();
	// 			flush();

	// 			unset($listData);
	// 			unset($list);
	// 			unset($value);

	// 			$i++;
	// 		}

	// 		if (isset($fp)) {
	// 			fclose($fp);
	// 			unset($fp);
	// 		}

	// 		//进行多个文件压缩
	// 		$zip         = new \ZipArchive();
	// 		$filenamezip = $fileName . "_订单数据.zip";
	// 		$zip->open($filenamezip, \ZipArchive::CREATE); //打开压缩包
	// 		foreach ($fileNameArr as $file) {
	// 			$zip->addFile($file, basename($file)); //向压缩包中添加文件
	// 		}
	// 		$zip->close(); //关闭压缩包
	// 		//输出压缩文件提供下载
	// 		header("Cache-Control: max-age=0");
	// 		header("Content-Description: File Transfer");
	// 		header('Content-disposition: attachment; filename=' . basename($filenamezip)); // 文件名
	// 		header("Content-Type: application/zip"); // zip格式的
	// 		header("Content-Transfer-Encoding: binary"); //
	// 		header('Content-Length: ' . filesize($filenamezip)); //
	// 		@readfile($filenamezip); //输出文件;
	// 		try {

	// 			if (file_exists($filenamezip)) {
	// 				unlink($filenamezip); //删除压缩包临时文件
	// 			}
	// 			foreach ($fileNameArr as $file) {
	// 				if (file_exists($file)) {
	// 					unlink($file); //删除csv临时文件
	// 				}
	// 			}
	// 		} catch (\Exception $e) {
	// 			trace($e->getMessage());
	// 		}
	// 		exit;

	// 		//      $while = true;
	// 		//      $while_num = 1;
	// 		//      //循环每一万数据查询一次保存在临时文件中
	// 		//      while ($while) {

	// 		// //数据写入csv
	// 		//       $csv_txt = '';
	// 		// foreach ($list as $key => $value) {
	// 		// 	$arr = [];
	// 		// 	foreach ($data_put_feild as $k => $v) {
	// 		// 		$value[$k] = str_replace(",","，",$value[$k]);
	// 		// 		$arr[] = "\t".$value[$k];
	// 		// 	}
	// 		// 	fputcsv($fp, $arr);
	// 		// }
	// 		// //保存到临时文件中
	// 		//     		if($while_num > 30 || !$list || empty($list) || COUNT($list) == 0)
	// 		//     		{
	// 		//       	$while = false;
	// 		//       	break;
	// 		//     		}
	// 		//      	unset($list);
	// 		//      	ob_flush();
	// 		//     		flush();
	// 		//     		$while_num++;
	// 		//      }
	// 	} catch (Exception $e) {
	// 		echo "导出文件出错了";
	// 	}

	// 	exit;

	// }

	/**
	 * 获取数据头
	 * @Author   lf
	 * @DateTime 2018-07-26T12:01:21+0800
	 * @param    [type]                   $type [description]
	 * @return   [type]                         [description]
	 */
	public function get_put_feild($type, $fshi = 'select') {
		$data = [];
		switch ($type) {
		case 'admin':
			$data = ['company_name' => "渠道", 'channel_order_id' => "渠道订单", 'order_id' => "平台订单", 'channel_bus_id' => "渠道模板", 'bus_push_sms' => "短信内容", 'sms_size' => "占用", 's_balance' => "剩余短信", 'price' => " 单 价 ", 'platfrom' => "通道", 'trade_id' => "通道订单", 'plat_bus_id' => "通道模板", 'isp_host' => "主机号/端口号", 'phones' => '目标号码', 'phone_size' => "号码总数", 'success_size' => "提交成功", 'success_num' => "成功", 'failure_size' => "失败", 'order_status' => "状态", 'order_msg' => "描述", 'create_time' => "下 单 时 间", 'plat_group' => ''];
			break;
		case 'channel':
			$data = ['company_name' => "渠道", 'channel_order_id' => "渠道订单号", 'channel_bus_id' => "渠道模板", 'bus_push_sms' => "短信内容", 'sms_size' => "短信占用", 's_balance' => "剩余短信", 'price' => " 单 价 ", 'order_id' => "平台订单号", 'isp_host' => "主机号/端口号", 'phones' => '目标号码', 'phone_size' => "号码总数", 'success_size' => "提交成功", 'success_num' => "成功", 'failure_size' => "失败", 'order_status' => "订单状态", 'order_msg' => "订单描述", 'create_time' => "下单时间"];
			break;
		case 'clerk':
			$data = ['company_name' => "渠道", 'channel_order_id' => "渠道订单号", 'channel_bus_id' => "渠道模板", 'bus_push_sms' => "短信内容", 'sms_size' => "短信占用", 's_balance' => "剩余短信", 'price' => " 单 价 ", 'order_id' => "平台订单号", 'isp_host' => "主机号/端口号", 'phones' => '目标号码', 'phone_size' => "号码总数", 'success_size' => "提交成功", 'success_num' => "成功", 'failure_size' => "失败", 'order_status' => "订单状态", 'order_msg' => "订单描述", 'create_time' => "下单时间"];
			break;
		case 'plat':
			$data = ['trade_id' => "通道订单号", 'plat_bus_id' => "通道模板", 'bus_push_sms' => "短信内容", 'sms_size' => "短信占用", 'order_id' => "平台订单号", 'isp_host' => "主机号/端口号", 'phones' => '目标号码', 'phone_size' => "号码总数", 'success_size' => "提交成功", 'success_num' => "成功", 'failure_size' => "失败", 'order_status' => "订单状态", 'order_msg' => "订单描述", 'create_time' => "下单时间"];
			break;

		default:
			# code...
			break;
		}

		//导出不需要目标号码
		if ($fshi == 'putout') {
			unset($data['phones']);
			unset($data['success_num']);
		}

		$getauth = session('auth');

		if ($getauth != '*') {
			$getfeild = Auth::where(['auth_pid' => '60', 'is_menu' => '2'])->find();

			$unfeild = explode(',', $getfeild['auth_c_a']);
			foreach ($unfeild as $key => $value) {
				unset($data[$value]);
			}
		}
		return $data;
	}

	/**
	 * 目标号码
	 * @Author   lf
	 * @DateTime 2018-07-10T14:32:58+0800
	 * @param    [type]                   $pid [description]
	 * @return   [type]                        [description]
	 */
	public function find_phones($id, $phone, $order) {
		$this->assign('id', $id);
		$this->assign('phone', $phone);
		$this->assign('order', $order);
		return $this->fetch();
	}
	public function findPhonesData() {

		//允许接收的请求变量
		$request = request()->only([
			'page'   => 1,
			'limit'  => 20,
			'id'     => '',
			'phone'  => '',
			'status' => '',
		]);

		$BusPreOrderPhone = new BusPreOrderPhone();

		return json(array_merge(["code" => 0, "msg" => ""], $BusPreOrderPhone->getOrderPhoneAll($request)));
	}

	/**
	 * 导出目标号码
	 * @Author   lf
	 * @DateTime 2018-08-02T13:02:58+0800
	 * @return   [type]                   [description]
	 */
	public function putout_phones() {
		set_time_limit(60);
		ini_set("memory_limit", "128M");

		//允许接收的请求变量
		$request = request()->only([
			'page'   => 1,
			'limit',
			'id'     => '',
			'phone'  => '',
			'status' => '',
		]);
		$request['limit'] = 9999999;
		if (empty($request['id'])) {
			return;
		}

		$BusPreOrderPhone = new BusPreOrderPhone();

		$data = $BusPreOrderPhone->getOrderPhoneAll($request);

		header('Content-Type: application/vnd.ms-execl');
		header('Content-Disposition: attachment;filename=目标号码_"' . uniqid() . '.csv');
		$fp = fopen('php://output', 'a');
		fwrite($fp, chr(0xEF) . chr(0xBB) . chr(0xBF)); //转码
		$feild = ['号码', '国家', '状态', '下单时间', '发送时间', '回调时间'];
		fputcsv($fp, $feild);

		foreach ($data['data'] as $key => $value) {
			$datalist   = [];
			$datalist[] = "\t" . $value['phone'];
			$datalist[] = "\t" . $value['country'];
			$datalist[] = "\t" . $value['status'];
			$datalist[] = "\t" . $value['create_time'];
			$datalist[] = "\t" . $value['send_time'];
			$datalist[] = "\t" . $value['callback_time'];

			fputcsv($fp, $datalist);
		}
		exit;

	}

	// 通道订单
	public function plat_list($id, $stime) {
		if (input('get.api')) {

			$request = input('get.');

			if (empty($id) || !is_numeric($id)) {

				return json(['code' => 1, 'msg' => '参数错误']);
			}

			$data = db('bus_add_order_' . $request['stime'])
				->alias('o')
				->field('o.bus_plat_id,o.plat_id as pladtid,o.group_flag,o.port_number,bp.platfrom')
				->where('o.table_order_id', '=', $id)
				->join('bus_platfrom bp', 'bp.plat_id=o.plat_id', 'left')
				->paginate($request['limit'])
				->each(function ($item, $key) {

					switch ($item['group_flag']) {
					case '0':

						$item['group_flag_'] = '省外通道';
						break;
					case '1':

						$item['group_flag_'] = '省内通道';
						break;
					case '2':

						$item['group_flag_'] = '重发通道';
						break;

					case NULL:

						$item['group_flag_'] = '非组合性通道';
						break;

					default:
						$item['group_flag_'] = '';
						break;
					}

					return $item;
				});

			$count = $data->total();

			$list = $data->toArray();

			$list = $list['data'];

			return json(['code' => 0, 'msg' => '', 'count' => $count, 'data' => $list]);
		} else {

			$this->assign('id', $id);
			$this->assign('stime', $stime);
			return $this->fetch();
		}
	}

}
